<?php

namespace App\Http\Controllers\Home;

use App\Http\Model\Article;
use App\Http\Model\Comment;
use App\Http\Model\Images;
use App\Http\Model\Star;
use App\Http\Model\User;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Session;

class UserController extends Controller
{
    /**
     * 用户中心
     * @return $this
     */
    public function userCenter(){
        /*获取收藏的数量*/
        $starNum=Star::where(['uid'=>Session::get('user')['id']])->where('type','<','3')->count();
        /*获取发布文章数量*/
        $ainum=0;
        if(!empty(Session::get('user')['is_author'])){
            if(Session::get('user')['role']==2){
                $ainum=Article::where(['user_id'=>Session::get('user')['id']])->count();
            }else if(Session::get('user')['role']==3){
                $ainum=Images::where(['user_id'=>Session::get('user')['id']])->count();
            }else if(Session::get('user')['role']==5){
                $ainum1=Article::where(['user_id'=>Session::get('user')['id']])->count();
                $ainum2=Images::where(['user_id'=>Session::get('user')['id']])->count();
                $ainum=$ainum1+$ainum2;
            }
        }
        /*关注的人*/
        $guanNum=Star::where(['uid'=>Session::get('user')['id'],'type'=>3])->count();
        /*未查看的评论回复*/
        $replys1=Comment::select('id')->where(['uid'=>Session::get('user')['id'],'type'=>1])->get()->all();
        $replys2=Comment::select('id')->where(['uid'=>Session::get('user')['id'],'type'=>2])->get()->all();
        $replyids1=$replyids2=[];
        foreach($replys1 as $reply){
            $replyids1[]=$reply->id;
        }
        foreach($replys2 as $reply){
            $replyids2[]=$reply->id;
        }
        $replyComments1=Comment::select('user.username','user.avatar','comment.cid','comment.id','comment.comment','comment.created_at','article.title','comment.type')
            ->join('user','user.id','=','comment.uid','left')
            ->join('article','article.id','=','comment.cid','left')
            ->whereIn('comment.reply',$replyids1)->where('comment.read',0)->orderBy('created_at','desc')->get()->all();
        $replyComments2=Comment::select('user.username','user.avatar','comment.cid','comment.id','comment.comment','comment.created_at','images.title','comment.type')
            ->join('user','user.id','=','comment.uid','left')
            ->join('images','images.id','=','comment.cid','left')
            ->whereIn('comment.reply',$replyids2)->where('comment.read',0)->orderBy('created_at','desc')->get()->all();
        $replyComments=array_merge($replyComments1,$replyComments2);
        return view('home.usercenter',compact('starNum','ainum','guanNum','replyComments'))->
        with(['title'=>Session::get('user')['username'],'authorinfo'=>'']);
    }

    /**
     * 更改评论回复状态已读
     * @return array
     */
    public function read(){
        if($input=Input::except('_token')){
            if(Comment::where('id',$input['id'])->update(['read'=>1])){
                return ['status'=>1];
            }else{
                return ['status'=>0];
            }
        }
    }

    /**
     * 设置头像
     * @return array
     */
    public function setAvatar(){
        if($input=Input::except('_token')){
            $id=Session::get('user')['id'];
            if(User::where('id',$id)->update($input)){
                $userinfo=Session::get('user');
                $userinfo['avatar']=$input['avatar'];
                session()->put('user',$userinfo);
                return ['status'=>1,'msg'=>'更新成功'];
            }else{
                return ['status'=>0,'msg'=>'更新失败'];
            }
        }
    }

    /**
     * 收藏文章,关注作者,评论点赞这三个功能
     * @return array
     */
    public function star(){
        if($input=Input::except('_token')){
            if(Session::get('user')){
                $insert['uid']=Session::get('user')['id'];
                $insert['type']=$input['type'];
                $insert['id']=$input['id'];
                if(Star::where($insert)->get()->all()){
                    if($input['type']==4){
                        $msg='您已经点赞';
                    }else if($input['type']==1 || $input['type']==2){
                        $msg='您已经收藏';
                    }else if($input['type']==3){
                        $msg='您已经关注';
                    }
                    return ['status'=>1,'msg'=>$msg];
                }
                if(Star::create($insert)){
                    if($input['type']==4){
                        Comment::where('id',$input['id'])->increment('like',1);
                        $msg='点赞成功';
                    }else if($input['type']==1 || $input['type']==2){
                        $msg='收藏成功';
                    }else if($input['type']==3){
                        $msg='关注成功';
                    }
                    return ['status'=>1,'msg'=>$msg];
                }else{
                    if($input['type']==4){
                        $msg='点赞失败';
                    }else if($input['type']==1 || $input['type']==2){
                        $msg='收藏失败';
                    }
                    return ['status'=>0,'msg'=>$msg];
                }
        }else{
                return ['status'=>0,'msg'=>'您未登录'];
            }
        }
    }

    /**
     * 取消关注作者
     * @return array
     */
    public function unstar(){
        if($input=Input::except('_token')){
            $input['uid']=Session::get('user')['id'];
            if(Star::where($input)->delete()){
                return ['status'=>1,'已经取消关注'];
            }else{
                return ['status'=>0,'取消关注失败'];
            }
        }
    }

    /**
     * 获取更多收藏的文章，图册
     * @param $page 页数
     * @return array
     */
    public function starAIs($page){
        return $this->getStarAI($page);
    }

    /**
     * 获取更多收藏的文章，图册
     * @param $page 页数
     * @return array
     */
    private function getStarAI($page){
        $uid=Session::get('user')['id'];
        $articleIDs=Star::select('id')->where(['uid'=>$uid,'type'=>1])->get()->all();
        $imageIDs=Star::select('id')->where(['uid'=>$uid,'type'=>2])->get()->all();
        $a=$b=[];
        foreach($articleIDs as $articleID){
            $a[]=$articleID['id'];
        }
        foreach($imageIDs as $imageID){
            $b[]=$imageID['id'];
        }
        $articleContent=DB::table('article')->select('article.title','article.created_at','article.cover',
            'article.banner','category.category',
            'article.id','article_content.content','user.username','user.avatar')
            ->join('article_content','article_content.article_id','=','article.id','left')
            ->join('user','user.id','=','article.user_id','left')
            ->join('category','category.id','=','article.category_id','left')
            ->where(['article.status'=>1])->whereIn('article.id',$a)->orderBy('article.created_at','desc')
            ->offset(($page-1)*12)->limit(12)->get();
        foreach($articleContent as $k=> $item){
            if(isset($item->content)){
                $articleContent[$k]->content=mb_substr(strip_tags(trim(strip_tags($item->content))),0,150,'utf-8');
            }
        }
        $imageContent=DB::table('images')->select('user.username','images.created_at','user.avatar',
            'images.title','images.images','images.id','category.category')
            ->join('user','user.id','=','images.user_id','left')
            ->join('category','category.id','=','images.category_id','left')
            ->where(['images.status'=>1])->whereIn('images.id',$b)->orderBy('images.created_at','desc')
            ->offset(($page-1)*12)->limit(12)->get();
        $mainContent=array_merge($articleContent,$imageContent);
        return $mainContent;
    }

    /**
     * 获取用户收藏的文章，图片等
     * @param $page 页数
     * @return $this
     */
    public function starAI($page){
        if($page<=0){
            $page=1;
        }
        $mainContent=$this->getStarAI(1);
        return view('home.starai',compact('mainContent'))->with(['title'=>'我的收藏','authorinfo'=>'']);
    }

    /**
     * 修改用户签名
     * @return array
     */
    public function modifyUser(){
        if($input=Input::except('_token')){
            if(User::where('id',Session::get('user')['id'])->update($input)){
                $userinfo=Session::get('user');
                if(isset($input['username'])){
                    $userinfo['username']=$input['username'];
                }else{
                    $userinfo['describe']=$input['describe'];
                }
                session()->put('user',$userinfo);
                return ['status'=>1,'msg'=>'修改成功'];
            }else{
                return ['status'=>0,'msg'=>'修改失败'];
            }
        }
    }

    /*
     * 作者文章列表
     */
    public function userArticle($page){
        $mainContent=$this->getUserArticles(1);
        return view('home.userarticle',compact('mainContent'))->with(['title'=>'我的发布','authorinfo'=>'']);
    }

    /**
     * 获取更多文章，图册。
     * @param $page 页数
     * @return array
     */
    public function userArticles($page){
        return $this->getUserArticles($page);
    }

    /**
     * 获取更多文章，图册。
     * @param $page 页数
     * @return array
     */
    private function getUserArticles($page){
        $articleContent=[];
        $imageContent=[];
        if(Session::get('user')['role']==2 || Session::get('user')['role']==5){
            $articleContent=DB::table('article')->select('article.title','article.created_at','category.category',
                'article.cover','article.banner','article.id','article_content.content','user.username','user.avatar')
                ->join('article_content','article_content.article_id','=','article.id','left')
                ->join('user','user.id','=','article.user_id','left')
                ->join('category','category.id','=','article.category_id','left')
                ->where(['article.user_id'=>Session::get('user')['id']])->orderBy('article.created_at','desc')
                ->offset(($page-1)*12)->limit(12)->get();
            foreach($articleContent as $k=> $item){
                if(isset($item->content)){
                    $articleContent[$k]->content=mb_substr(strip_tags(trim(strip_tags($item->content))),0,150,'utf-8');
                }
            }
        }
        if(Session::get('user')['role']==3 || Session::get('user')['role']==5){
            $imageContent=DB::table('images')->select('user.username','user.avatar','images.created_at','images.title',
                'images.images','images.id','category.category')
                ->join('user','user.id','=','images.user_id','left')
                ->join('category','category.id','=','images.category_id','left')
                ->where(['images.user_id'=>Session::get('user')['id']])->orderBy('images.created_at','desc')
                ->offset(($page-1)*12)->limit(12)->get();
        }
        return array_merge($articleContent,$imageContent);
    }

    /**
     * 关注的作者
     * @return $this
     */
    public function attention(){
        $attentions=Star::select('star.id','user.username','user.avatar','user.describe','user.role','star.created_at')
            ->join('user','user.id','=','star.id','left')
            ->where(['star.uid'=>Session::get('user')['id'],'star.type'=>3,'user.status'=>1,'is_author'=>1])->get()->all();
        $fansnum=[];
        foreach($attentions as $at){
            $fansnum[]=Star::join('user','user.id','=','star.id','left')->where(['star.id'=>$at['id'],'star.type'=>3,
                'user.status'=>1,'is_author'=>1])->count();
        }
        return view('home.attention',compact('attentions','fansnum'))->with(['title'=>'我的关注','authorinfo'=>'']);
    }

    /**
     * 这个作者的发布
     * @param $author_id 作者id
     * @param $page 页数
     * @return $this
     */
    public function authorarticle($author_id,$page){
        $info=User::select('id','username','avatar','created_at','describe','role')->find($author_id);
        $fansnum=Star::join('user','user.id','=','star.id','left')->where(['star.id'=>$author_id,'star.type'=>3,
            'user.status'=>1,'is_author'=>1])->count();
        $mainContent=$this->getAuthorArticles($author_id,1,$info);
        return view('home.authorarticle',compact('info','fansnum','mainContent','author_id'))
            ->with(['title'=>$info->username.'的文章','authorinfo'=>'']);
    }

    /**
     * 获取这个作者的所有作品
     * @param $author_id 作者id
     * @param $page 页数
     * @param $info 作者信息
     * @return array
     */
    private function getAuthorArticles($author_id,$page,$info){
        $as=$is=[];
        if($info->role==2 || $info->role==5){
            $as=DB::table('article')->select('article.title','article.created_at','article.cover','article.banner',
                'article.id','article_content.content','user.username','user.avatar','category.category')
                ->join('article_content','article_content.article_id','=','article.id','left')
                ->join('user','user.id','=','article.user_id','left')
                ->join('category','category.id','=','article.category_id','left')
                ->where(['article.user_id'=>$author_id])->orderBy('article.created_at','desc')->offset(($page-1)*12)->limit(12)->get();
            foreach($as as $k=> $item){
                if(isset($item->content)){
                    $as[$k]->content=mb_substr(strip_tags(trim(strip_tags($item->content))),0,150,'utf-8');
                }
            }
        }
        if($info->role==3 || $info->role==5){
            $is=DB::table('images')->select('user.username','user.avatar','images.created_at','images.title','images.images',
                'images.id','category.category')
                ->join('user','user.id','=','images.user_id','left')
                ->join('category','category.id','=','images.category_id','left')
                ->where(['images.user_id'=>$author_id])->orderBy('images.created_at','desc')->offset(($page-1)*12)->limit(12)->get();
        }
        $mainContent=array_merge($as,$is);
        return $mainContent;
    }

    /**
     * 这个作者更多的的发布
     * @param $author_id 作者id
     * @param $page 页数
     * @return array
     */
    public function authorArticles($author_id,$page){
        $info=User::select('id','username','avatar','created_at','describe','role')->find($author_id);
        return $this->getAuthorArticles($author_id,$page,$info);
    }

    /**
     * 退出登录
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function logOut(){
        session(['user'=>'']);
        return redirect('index');
    }
}
